<template>
  <div class="form-control">
    <je-tabs v-model:activeKey="activeKey">
      <je-tab-pane key="1" tab="字段赋值">
        <FieldAssign
          :field-datas="fieldAssignDatas"
          :grid-height="gridHeight"
          :field-assignment="fieldAssignment"
          :node-id="nodeId"
          @setConfigData="setConfigData"
        />
      </je-tab-pane>
      <je-tab-pane key="2" tab="字段控制">
        <FieldControl
          :field-datas="fieldControlDatas"
          :field-control="fieldControl"
          :node-id="nodeId"
          :grid-height="gridHeight"
          @setConfigData="setConfigData"
        />
      </je-tab-pane>
      <je-tab-pane key="3" tab="可用按钮">
        <ButtonControl
          :func-info="funcInfo"
          :node-id="nodeId"
          :task-form-button="taskFormButton"
          @setConfigData="setConfigData"
        />
      </je-tab-pane>
      <je-tab-pane key="4" tab="子功能">
        <ChildfuncControl
          :func-info="funcInfo"
          :node-id="nodeId"
          :task-child-func="taskChildFunc"
          @setConfigData="setConfigData"
        />
      </je-tab-pane>
    </je-tabs>
  </div>
</template>

<script>
  import { defineComponent, ref, onMounted, watch, reactive } from 'vue';
  import { Tabs, Modal } from '@jecloud/ui';
  import { getData } from '@/api/index';
  import { cloneDeep, encode, isEmpty } from '@jecloud/utils';

  import FieldAssign from './components/field-assign.vue';
  import FieldControl from './components/field-control.vue';
  import ButtonControl from './components/button-control.vue';
  import ChildfuncControl from './components/childfunc-control.vue';

  export default defineComponent({
    name: 'FormControl',
    components: {
      JeTabs: Tabs,
      JeTabPane: Tabs.TabPane,
      FieldAssign,
      FieldControl,
      ButtonControl,
      ChildfuncControl,
    },
    props: {
      funcInfo: {
        type: Object,
        default: () => {
          return {};
        },
      },
      formConfig: {
        type: Object,
        default: () => {
          return {};
        },
      },
      nodeId: {
        type: String,
        default: '',
      },
    },
    setup(props) {
      const activeKey = ref('1');
      //字段的数据
      const fieldAssignDatas = ref([]);
      const fieldControlDatas = ref([]);
      const gridHeight = ref(0);

      //字段赋值列表数据
      const fieldAssignment = ref(props.formConfig.fieldAssignment);
      //字段控制列表数据
      const fieldControl = ref(props.formConfig.fieldControl);
      //可用按钮列表数据
      const taskFormButton = ref(props.formConfig.taskFormButton);
      //子功能列表数据
      const taskChildFunc = ref(props.formConfig.taskChildFunc);

      watch(
        () => props.nodeId,
        () => {
          fieldAssignment.value = props.formConfig.fieldAssignment;
          fieldControl.value = props.formConfig.fieldControl;
          taskFormButton.value = props.formConfig.taskFormButton;
          taskChildFunc.value = props.formConfig.taskChildFunc;
        },
      );

      onMounted(() => {
        getFieldDatas();
      });

      //选择的功能发生变化需要刷新列表数据
      watch(
        () => props.funcInfo.funcId,
        () => {
          getFieldDatas();
        },
      );

      //获得功能的字段信息
      const getFieldDatas = () => {
        const funcId = props.funcInfo.funcId;
        //如果funcId为空就不执行
        if (isEmpty(funcId)) {
          fieldAssignDatas.value = [];
          fieldControlDatas.value = [];
          gridHeight.value = 0;
          return false;
        }
        const params = {
          tableCode: 'JE_CORE_RESOURCEFIELD',
          j_query: encode({
            custom: [
              {
                code: 'RESOURCEFIELD_FUNCINFO_ID',
                type: '=',
                value: funcId,
                cn: 'and',
              },
              {
                code: 'RESOURCEFIELD_XTYPE',
                type: 'notIn',
                value: ['child', 'fieldset'],
                cn: 'and',
              },
            ],
            order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
          }),
          limit: '-1',
        };
        getData(params, { pd: 'meta' })
          .then((data) => {
            fieldAssignDatas.value = doSortAssignDatas(cloneDeep(data.rows));
            fieldControlDatas.value = doSortControlDatas(cloneDeep(data.rows));
            if (data.rows.length > 0) {
              gridHeight.value = data.rows.length * 32 + 32;
            }
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };

      // 字段赋值面板排序 先排业务字段，再排系统字段。内部排序为：字段编码排序。
      const doSortAssignDatas = (datas) => {
        let sortDatas = [];
        if (datas.length > 0) {
          // 字段编码排序
          const newDatas = sortObjectsByProperty(datas, 'RESOURCEFIELD_CODE');
          const syDatas = [],
            noSyDatas = [];
          // 先排业务字段，再排系统字段
          newDatas.forEach((item) => {
            if (item.RESOURCEFIELD_CODE.substring(0, 3) == 'SY_') {
              syDatas.push({ code: item.RESOURCEFIELD_CODE, name: item.RESOURCEFIELD_NAME });
            } else {
              noSyDatas.push({ code: item.RESOURCEFIELD_CODE, name: item.RESOURCEFIELD_NAME });
            }
          });
          sortDatas = noSyDatas.concat(syDatas);
        }
        return sortDatas;
      };

      // 字段控制面板排序 先排 展示字段，再排隐藏字段。内部排序为：顺序号排序。
      const doSortControlDatas = (datas) => {
        let sortDatas = [];
        if (datas.length > 0) {
          const hideDatas = [],
            showDatas = [];
          datas.forEach((item) => {
            if (item.RESOURCEFIELD_HIDDEN == '1') {
              hideDatas.push({ code: item.RESOURCEFIELD_CODE, name: item.RESOURCEFIELD_NAME });
            } else {
              showDatas.push({ code: item.RESOURCEFIELD_CODE, name: item.RESOURCEFIELD_NAME });
            }
          });
          sortDatas = showDatas.concat(hideDatas);
        }
        return sortDatas;
      };

      //
      const sortObjectsByProperty = (list, property) => {
        return list.sort((a, b) => {
          const propA = a[property].toUpperCase();
          const propB = b[property].toUpperCase();
          if (propA < propB) {
            return -1;
          }
          if (propA > propB) {
            return 1;
          }
          return 0;
        });
      };

      //给主数据赋值
      const setConfigData = (obj) => {
        const { type, datas } = obj;
        switch (type) {
          //字段赋值列表数据
          case 'fieldAssignment':
            Object.assign(fieldAssignment.value, datas);
            for (let key in fieldAssignment.value) {
              if (!datas[key]) {
                delete fieldAssignment.value[key];
              }
            }
            break;
          //字段控制列表数据
          case 'fieldControl':
            Object.assign(fieldControl.value, datas);
            for (let key in fieldControl.value) {
              if (!datas[key]) {
                delete fieldControl.value[key];
              }
            }
            break;
          //可用按钮列表数据
          case 'taskFormButton':
            Object.assign(taskFormButton.value, datas);
            for (let key in taskFormButton.value) {
              if (!datas[key]) {
                delete taskFormButton.value[key];
              }
            }
            break;
          //子功能列表数据
          case 'taskChildFunc':
            Object.assign(taskChildFunc.value, datas);
            for (let key in taskChildFunc.value) {
              if (!datas[key]) {
                delete taskChildFunc.value[key];
              }
            }
            break;
        }
      };

      return {
        activeKey,
        fieldAssignment,
        fieldControl,
        taskFormButton,
        taskChildFunc,
        setConfigData,
        gridHeight,
        fieldAssignDatas,
        fieldControlDatas,
      };
    },
  });
</script>

<style lang="less">
  .form-control {
    .ant-tabs-nav {
      height: 32px;
      margin: 0;
      padding-left: 10px;
    }
  }
</style>
